<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\warehouse\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\warehouse\model\WareHouse as WareHouseModel;
use think\Db;
use util\Tree;
/**
 * 仓库配送区域管理控制器
 * @package app\warehouse\controller
 */
class DeliveryArea extends Admin
{
    /**
     * 仓库配送区域列表
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function index($id=null)
    {
        $other_deliveryarea=db('warehouse_list')->where('warehouseid','neq',$id)->column('deliveryarea');
        if(empty(array_filter($other_deliveryarea))){
            $areas = db("admin_area")->order('id')->column('id,pid,name');
        }else{
            $pids=db("admin_area")->where('pid',0)->column('id');
            $newbox=array_diff(explode(",",implode(",",array_filter($other_deliveryarea))),$pids);

            $areas = db("admin_area")->where('id','not in',implode(",",$newbox))->order('id')->column('id,pid,name');
        }
        $areas = Tree::toLayer($areas);
        foreach ($areas as $key => $value) {
            # code...
            if(empty($value['child'])) unset($areas[$key]);
        }    
        $this->assign('areas', $areas);
        $deliveryarea=db('warehouse_list')->where('warehouseid','eq',$id)->value('deliveryarea');
        $this->assign('deliveryarea', $deliveryarea);
        $this->assign('warehouseid',$id);
        return $this->fetch();
    }

    public function dosave(){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['area_node'])){
                $this->error('请至少选择一个配送区域');
            }
            $updatedata['warehouseid']=$data['warehouseid'];
            $updatedata['deliveryarea']=implode(',',$data['area_node']);

            if (WareHouseModel::update($updatedata)) {
                $this->success('设置成功', null, ['_close_pop' => 1,'_parent_reload'=>1]);
            } else {
                return $this->error('设置失败');
            }
        }
    }
}